package com.china08.yxyapi.api.comm.upload;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.entity.db.lessons.YxyLessonsVideo;
import com.china08.yxyapi.model.YxyApiRespModel;
import com.china08.yxyapi.repository.db.YxyLessonsVideoRepository;
import com.china08.yxyapi.util.YxyResUtil;

/**
 * 上传视频
 * 
 * @author zd.Jin
 *
 *
 */

@CrossOrigin
@RestController
public class UploadFileResController extends YxyApiBaseController {
    private static final Logger LOGGER = LoggerFactory.getLogger(UploadFileResController.class);

    @Value("${weike.storage.upload.video}")
    private String uploadBasePath;

    @Autowired
    private YxyLessonsVideoRepository yxyLessonsVideoRepository;

    @SuppressWarnings("unused")
    @RequestMapping(value = "/api_yw/comm/upload/file", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Object process(HttpServletRequest request, HttpServletResponse response, @RequestPart MultipartFile file, @RequestParam(value = "mediaId") String mediaId, RespModel respModel) throws IOException {

        // md5
        String md5 = DigestUtils.md5Hex(file.getBytes());
        // 根据MD5值 查看数据库中是否存在
        List<YxyLessonsVideo> findByMd5 = yxyLessonsVideoRepository.findByMd5OrderByCreatedDateAsc(md5);

        YxyLessonsVideo findByMd5Resource = null;
        if (CollectionUtils.isNotEmpty(findByMd5)) {
            findByMd5Resource = findByMd5.get(0);
            String title = StringUtils.substringBefore(file.getOriginalFilename(), ".");
            findByMd5Resource.setFileName(title);// 微课名称
            yxyLessonsVideoRepository.saveAndFlush(findByMd5Resource);
            respModel = new RespModel();
            respModel.mediaId = findByMd5Resource.getId();
            respModel.title = findByMd5Resource.getFileName();
            respModel.duration = findByMd5Resource.getDuration();
            respModel.setMessage("视频已存在");
            return respModel;
        }
        // 后缀名
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        // 不为空
        String location = null;
        Integer duration = 0;
        Integer convertStatus = 0;
        if (findByMd5Resource != null) {
            location = findByMd5Resource.getLocation();
            duration = findByMd5Resource.getDuration();
            if (duration == 0) {
                Long duration1 = 0L;
                try {
                    duration1 = YxyResUtil.getDuration(uploadBasePath + location) / 1000;
                } catch (Exception e) {
                }
                if (duration1 != null) {
                    duration = Integer.valueOf(duration1 + "");
                }
            }
            convertStatus = findByMd5Resource.getStatus();
        } else {
            // 视频路径
            String path = YxyResUtil.getPath();
            String savePath = uploadBasePath + path;
            File sf = new File(savePath);
            String realPath = sf.getPath() + File.separator + md5.substring(0, 2) + File.separator + md5 + "." + extension;
            FileUtils.forceMkdir(sf);
            FileUtils.writeByteArrayToFile(new File(realPath), file.getBytes());
            location = path + "/" + md5.substring(0, 2) + "/" + md5 + "." + extension;
            // 时长
            Long duration1 = 0L;
            try {
                duration1 = YxyResUtil.getDuration(uploadBasePath + location) / 1000;
            } catch (Exception e) {
                // e.printStackTrace();
            }
            if (duration1 != null) {
                duration = Integer.valueOf(duration1 + "");
            }
        }
        // 微课
        YxyLessonsVideo yxyLessonsVideo = null;

        if (StringUtils.isNotBlank(mediaId)) {
            yxyLessonsVideo = yxyLessonsVideoRepository.findById(mediaId);
            Assert.notNull(yxyLessonsVideo, "找不到微课，请刷新页面");
        } else {
            yxyLessonsVideo = new YxyLessonsVideo();
            yxyLessonsVideo.setId(UUID.randomUUID().toString().replace("-", ""));
            yxyLessonsVideo.setStatus(-1);
        }

        // 转码状态
        convertStatus = convertStatus == 2 ? convertStatus : 0;
        yxyLessonsVideo.setStatus(convertStatus);
        // 上传信息
        yxyLessonsVideo.setLocation(location);

        yxyLessonsVideo.setFileSize((int) file.getSize());

        yxyLessonsVideo.setExtension(extension);

        String title = StringUtils.substringBefore(file.getOriginalFilename(), ".");

        yxyLessonsVideo.setFileName(title);// 微课名称

        yxyLessonsVideo.setMd5(md5);
        // duration = 10;
        yxyLessonsVideo.setDuration((int) duration);// 默认是0

        // 上传者信息 使用云校接口
        yxyLessonsVideo.setUserId("ff808081475757bc01475d0f6a9b00ed"); // 作者

        yxyLessonsVideoRepository.saveAndFlush(yxyLessonsVideo);

        respModel = new RespModel();
        respModel.mediaId = yxyLessonsVideo.getId();
        respModel.title = yxyLessonsVideo.getFileName();
        respModel.duration = yxyLessonsVideo.getDuration();
        respModel.setMessage("上传视频成功");
        return respModel;
    }

    public static class RespModel extends YxyApiRespModel {
        public String md5;
        public String location;
        public long size;
        public String extension;
        public String mediaId;// 微课id
        public String title;// 微课名称
        public Integer duration;// 时长--秒
    }
}